package com.wangsong.controller;


import com.wangsong.model.MUserGroups;
import com.wangsong.model.User;
import com.wangsong.model.UserValidator;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;


@Controller
@ControllerAdvice
public class ValidatedController {


    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(@Validated({MUserGroups.MUserGroupsAdd.class}) UserValidator user) {//, BindingResult bindingResult
        return "1";
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(@Validated({MUserGroups.MUserGroupsUpdate.class}) UserValidator user) {//, BindingResult bindingResult
        return "2";
    }

    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public List<FieldError> handleBindException(BindException e) throws BindException {
        // ex.getFieldError():随机返回一个对象属性的异常信息。如果要一次性返回所有对象属性异常信息，则调用ex.getAllErrors()
        List<FieldError> fieldErrors = e.getFieldErrors();


        return fieldErrors;
    }

}
